package com.zfc.life.utils.file;

import com.zfc.life.config.QiNiuYunConfig;
import com.zfc.life.config.Xem;
import com.zfc.life.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author zfc
 * @Date 2024/8/13 14:41
 * @Description FileUploadUtils
 */
public class FileUploadUtils {


    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file) throws IOException {

        //1、原始文件名
        String originalFilename = file.getOriginalFilename();
        //2、截取原始文件名的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3、构造新的文件名
        String objectName = UUID.randomUUID().toString() + extension;

        //4、获取文件存储路径
        String directory = Xem.directory + byFileSelectDirectory(objectName) + StringUtils.yearAndMonthFolder();

        File folder = new File(directory);
        //5、如果文件夹不存在，则创建
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //6、根据目录和对象名称创建目标文件
        File destFile = new File(directory, objectName);

        //7、将源文件传输到目标文件
        file.transferTo(destFile);

        return "/profile"+byFileSelectDirectory(objectName) + StringUtils.yearAndMonthFolder()+ objectName;
    }

    public static String byFileSelectDirectory(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        System.out.println("suffix = " + suffix);
        if (suffix.equals("jpg") || suffix.equals("png") || suffix.equals("gif") || suffix.equals("jpeg")) {
            return "/image/";
        } else if (suffix.equals("mp4") || suffix.equals("avi") || suffix.equals("rmvb")) {
            return "/video/";
        }
        return "";
    }

    /**
     * 删除文件
     * @param filePath
     */
    public static void deleteFile(String filePath) {
        String path = filePath.substring(8);

        String joinPath = Xem.directory + path;
        File file = new File(joinPath);
        if (file.exists()) {
            file.delete();
        }
    }
}
